package com.cloud.tsp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.api.domain.report.ArealDistributionExcel;
import com.cloud.api.domain.stats.ArealDistribution;
import com.cloud.api.domain.stats.ArealExcel;
import com.cloud.api.domain.stats.QueryAreal;
import com.cloud.api.utils.ExcelUtils;
import com.cloud.mybatis.domain.PageModelNew;
import com.cloud.mybatis.domain.TableDataInfo;
import com.cloud.tsp.config.MysqlConfig;
import com.cloud.tsp.mapper.ArealDistributionMapper;
import com.cloud.tsp.service.EmailService;
import com.cloud.tsp.service.IArealDistributionService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * <p>
 * OLAP 服务实现类
 * </p>
 *
 * @author haohaibo
 * @since 2023-12-28
 */
@Service("arealDistributionService")
public class ArealDistributionServiceImpl extends ServiceImpl<ArealDistributionMapper, ArealDistribution> implements IArealDistributionService {

    @Resource
    private ArealDistributionMapper arealDistributionMapper;
    @Resource
    private MessageSource messageSource;

    @Autowired
    private MysqlConfig mysqlConfig;
    @Autowired
    private EmailService emailService;


    @Override
    public TableDataInfo<ArealDistribution> selectArealDistribution(QueryAreal para) {
//        getPermissions(para);
        Page<ArealDistribution> page = new Page<>();
        page.setCurrent(para.getPage());
        page.setSize(para.getPageSize());
        IPage<ArealDistribution> data = arealDistributionMapper.selectArealDistribution(page, para);
        desensitize(data.getRecords());
        return TableDataInfo.build(data);
    }

    public void desensitize(List<ArealDistribution>list){
        for (ArealDistribution arealDistribution : list) {
            arealDistribution.setVin(StrUtil.hide(arealDistribution.getVin(), 8, 11));
            if (StringUtil.isNotBlank(arealDistribution.getLicenseNumber())){
                if ("oil".equals(arealDistribution.getVehicleType())){
                    arealDistribution.setLicenseNumber(StrUtil.hide(arealDistribution.getLicenseNumber(), 3, 6));
                }else {
                    arealDistribution.setLicenseNumber(StrUtil.hide(arealDistribution.getLicenseNumber(), 4, 7));
                }
            }
        }
    }


    /*public void getPermissions(QueryAreal para){
        para.setDataScope(LoginHelper.getDataScope());
        if (para.getDataScope() == 5){
            R<SystemRoleDto> roleDetail = systemRoleOpenFeignService.getById(new StrVo(LoginHelper.getUserLogin().getRoleId()));
            String[] split = roleDetail.getData().getDeptIds().split(",");
            List<String> deptIds = new ArrayList<>(Arrays.asList(split));
            para.setDeptIds(deptIds);
        }else {
            List<String> list = new ArrayList<>();
            list.add(LoginHelper.getUserLogin().getDeptId());
            para.setDeptIds(list);
        }
    }*/

    @Override
    public void exportArealDistribution(QueryAreal para, HttpServletResponse response) throws IOException {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.arealDistribution";
        List<ArealDistribution> data = arealDistributionMapper.selectArealConditions(para);
        List<ArealExcel> list = new ArrayList<>();
        for(ArealDistribution arealDistribution : data){
            ArealExcel arealExcel = new ArealExcel();
            BeanUtils.copyProperties(arealDistribution,arealExcel);
            if (arealDistribution.getProvince() != null && arealDistribution.getCity() != null){
                arealExcel.setAdministrative(arealDistribution.getProvince()+arealDistribution.getCity());
            }
            arealExcel.setVin(StrUtil.hide(arealDistribution.getVin(), 8, 11));
            if (StringUtil.isNotBlank(arealDistribution.getLicenseNumber())){
                if ("oil".equals(arealDistribution.getVehicleType())){
                    arealExcel.setLicenseNumber(StrUtil.hide(arealDistribution.getLicenseNumber(), 3, 6));
                }else {
                    arealExcel.setLicenseNumber(StrUtil.hide(arealDistribution.getLicenseNumber(), 4, 7));
                }
            }
            list.add(arealExcel);
        }
        fileName = messageSource.getMessage(fileName, null, fileName, locale);
        ExcelUtils.export(response,fileName,list,ArealExcel.class);
    }

    @Override
    public void exportArealDistributionList(HttpServletResponse response) {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.arealDistribution";
        List<ArealDistributionExcel> data = arealDistributionMapper.exportArealDistributionList(mysqlConfig.getDataSource());
        fileName = messageSource.getMessage(fileName, null, fileName, locale);
        ExcelUtils.export(response,fileName,data,ArealDistributionExcel.class);
    }

    @Override
    public TableDataInfo<ArealDistributionExcel> selectArealDistributionList(PageModelNew para) {
        Page<ArealDistribution> page = new Page<>();
        page.setCurrent(para.getPage());
        page.setSize(para.getPageSize());
        IPage<ArealDistributionExcel> data = arealDistributionMapper.selectArealDistributionList(page, mysqlConfig.getDataSource());
        return TableDataInfo.build(data);
    }

    @Override
    public void exportMailArealDistributionList() {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.arealDistribution";
        List<ArealDistributionExcel> data = arealDistributionMapper.exportArealDistributionList(mysqlConfig.getDataSource());
        fileName = messageSource.getMessage(fileName, null, fileName, locale);
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 导出Excel文件到ByteArrayOutputStream
            ExcelUtils.export(outputStream, fileName, data, ArealDistributionExcel.class);
            // 获取字节数组副本，用于后续邮件发送
            byte[] fileBytes = outputStream.toByteArray();
            // 异步发送邮件
            emailService.sendEmailAsync("车辆各省市数据分布导出", "请查看附件中的车辆各省市数据分布数据。", fileName + ".xlsx", fileBytes);
        } catch (IOException e) {
            log.error("导出Excel文件失败", e);
        }
    }
}